package com.auth.gateway.service;

import com.auth.gateway.model.LoginSession;
import com.auth.gateway.model.SystemLoginConfig;
import com.auth.gateway.util.HtmlParserUtil;
import com.jayway.jsonpath.JsonPath;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Component
public class CsrfTokenLoginStrategy implements LoginStrategy {

    private final WebClient webClient = WebClient.create();

    @Override
    public Mono<LoginSession> login(String userId, SystemLoginConfig config) {
        return webClient.get()
                .uri(config.getCsrfPageUrl())
                .retrieve()
                .bodyToMono(String.class)
                .flatMap(html -> {
                    String csrfToken = HtmlParserUtil.extractCsrf(html, config.getCsrfFieldName());
                    return webClient.post()
                            .uri(config.getLoginUrl())
                            .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                            .header(config.getCsrfHeaderName(), csrfToken)
                            .body(BodyInserters.fromFormData(config.getUsernameParam(), userId)
                                    .with(config.getPasswordParam(), config.getStaticPassword()))
                            .retrieve()
                            .bodyToMono(String.class)
                            .map(resp -> {
                                String token = JsonPath.read(resp, "$." + config.getTokenField());
                                LoginSession session = new LoginSession();
                                session.setSystemCode("legacy-c");
                                session.getHeaders().put(config.getHeaderName(), "Bearer " + token);
                                return session;
                            });
                });
    }
}